package com.stjb.furns.web;

import com.stjb.furns.entity.Furn;
import com.stjb.furns.entity.Page;
import com.stjb.furns.service.FurnsService;
import com.stjb.furns.service.impl.FurnsServiceImpl;
import com.stjb.furns.utils.DataUtils;
import com.stjb.furns.utils.WebUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.UUID;

/**
 * @author situ
 * @version 1.0
 * @date 2025/5/26 21:56
 * @Description:
 */
public class FurnServlet extends BasicServlet {

    private FurnsService furnsService = new FurnsServiceImpl();

    /**
     * 使用模板设计+反射+动态绑定的机制调用list方法
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // System.out.println("ok");
        List<Furn> furns = furnsService.queryFurns();
        System.out.println(furns);

        // //测试
        // for (Furn furn : furns) {
        //     System.out.println(furn);
        // }

        //把furns集合放入request域
        req.setAttribute("furns", furns);
        System.out.println("首页家居展示= " + furns);
        //请求转发
        req.getRequestDispatcher("/views/manage/furn_manage.jsp").forward(req, resp);
    }


    /**
     * 处理添加家居请求
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取添加数据

        String name = req.getParameter("name");
        String maker = req.getParameter("maker");
        String price = req.getParameter("price");
        String sales = req.getParameter("sales");
        String stock = req.getParameter("stock");

        //后台数据校验

        // try {
        //     int i = Integer.parseInt(sales);
        // } catch (NumberFormatException e) {
        //     req.setAttribute("msg","销售数据格式不对");
        //     req.getRequestDispatcher("/views/manage/furn_add.jsp").forward(req,resp);
        //     return;
        // }

        //图片路径使用默认
        Furn furn = null;
        try {
            furn = new Furn(null, name, maker, new BigDecimal(price),
                    new Integer(sales), new Integer(stock), "assets/images/product-image/default.jpg");
        } catch (NumberFormatException e) {
            req.setAttribute("msg", "添加数据格式不正确");
            req.getRequestDispatcher("/views/manage/furn_add.jsp").forward(req, resp);
            return;
        }
        furnsService.addFurn(furn);
        //请求转发到家具显示页面
        // req.getRequestDispatcher("/manage/furnServlet?action=list").forward(req,resp);
        //请求转发会造成添加重复 所以用重定向
        //重新发送请求 路径需要完整
        resp.sendRedirect(req.getContextPath() + "/manage/furnServlet?action=page&pageNo=" + req.getParameter("pageNo"));
    }

    /**
     * 根据id删除家具
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //防止非数字字符串
        int id = DataUtils.parseInt(req.getParameter("id"), 0);
        furnsService.deleteFurnById(id);
        // 重定向显示
        resp.sendRedirect(req.getContextPath() + "/manage/furnServlet?action=page&pageNo=" + req.getParameter("pageNo"));
    }

    /**
     * 处理回显家居信息请求
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void showFurn(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // String id = req.getParameter("id");
        int id = DataUtils.parseInt(req.getParameter("id"), 0);
        Furn furn = furnsService.queryFurnById(id);
        req.setAttribute("furn", furn);

        //将pageNo保存
        // req.setAttribute("pageNo",req.getParameter("pageNo"));
        // System.out.println(furn);
        //请求转发
        req.getRequestDispatcher("/views/manage/furn_update.jsp").forward(req, resp);
    }

    /**
     * 更新家居信息
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        int id = DataUtils.parseInt(req.getParameter("id"), 0);
        //获取对应furn对象
        Furn furn = furnsService.queryFurnById(id);
        if (furn == null) {
            return;
        }

        //1. 判断是不是文件表单(enctype="multipart/form-data")
        if (ServletFileUpload.isMultipartContent(req)) {
            // 创建 DiskFileItemFactory 对象, 用于构建一个解析上传数据的工具对象
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            //创建一个解析上传数据的工具对象
            ServletFileUpload servletFileUpload =
                    new ServletFileUpload(diskFileItemFactory);
            //解决接收到文件名是中文乱码问题
            servletFileUpload.setHeaderEncoding("utf-8");
            //servletFileUpload 对象可以把表单提交的数据text / 文件
            //将其封装到 FileItem 文件项中
            try {
                //前端提交的表单数据在这里
                List<FileItem> list = servletFileUpload.parseRequest(req);
                //遍历，并分别处理
                for (FileItem fileItem : list) {
                    //System.out.println("fileItem=" + fileItem);
                    //判断是不是一个文件
                    if (fileItem.isFormField()) {//如果是true就是文本 input text(普通表单字段)

                        if ("name".equals(fileItem.getFieldName())) {
                            furn.setName(fileItem.getString("utf-8"));
                        } else if ("maker".equals(fileItem.getFieldName())) {
                            furn.setMaker(fileItem.getString("utf-8"));
                        } else if ("price".equals(fileItem.getFieldName())) {
                            furn.setPrice(new BigDecimal(fileItem.getString()));
                        } else if ("sales".equals(fileItem.getFieldName())) {
                            furn.setSales(new Integer(fileItem.getString()));
                        } else if ("stock".equals(fileItem.getFieldName())) {
                            furn.setStock(new Integer(fileItem.getString()));
                        }

                    } else {//是一个文件

                        //获取上传的文件的名字
                        String name = fileItem.getName();

                        //文件名不为空才处理 == 前端改变了图片再处理
                        if (!"".equals(name)) {
                            //把这个上传到 服务器的 temp下的文件保存到指定的目录
                            //1.指定一个目录 网站工作目录
                            String filePath = "/" + WebUtils.FURN_IMG_DIRECTORY;
                            //2. 获取到完整目录
                            String fileRealPath =
                                    req.getServletContext().getRealPath(filePath);
                            //3. 创建这个上传的目录
                            File fileRealPathDirectory = new File(fileRealPath);
                            if (!fileRealPathDirectory.exists()) {//不存在，就创建
                                fileRealPathDirectory.mkdirs();//创建
                            }

                            //4. 将文件拷贝到fileRealPathDirectory目录
                            //   对上传的文件名进行处理, 前面增加一个前缀，保证是唯一
                            name = UUID.randomUUID().toString() + "_" + System.currentTimeMillis() + "_" + name;
                            String fileFullPath = fileRealPathDirectory + "/" + name;
                            fileItem.write(new File(fileFullPath));//将上传的文件保存到out文件

                            fileItem.getOutputStream().close();//关闭流

                            //更新家居的路径
                            furn.setImgPath(WebUtils.FURN_IMG_DIRECTORY + "/" + name);
                        }
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            // System.out.println("不是文件表单...");
        }

        //更新furn对象
        furnsService.updateFurn(furn);

        //请求转发
        req.getRequestDispatcher("/views/manage/update_ok.jsp").forward(req, resp);

    }


    // protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //     //接收前端信息 封装到furn
    //     Furn furn = DataUtils.copyParamToBean(req.getParameterMap(), new Furn());
    //     // System.out.println(furn);
    //     furnsService.updateFurn(furn);
    //     //重定向到家居显示
    //     resp.sendRedirect(req.getContextPath()+"/manage/furnServlet?action=page&pageNo="+req.getParameter("pageNo"));
    // }

    /**
     * 处理分页请求
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void page(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        int pagNo = DataUtils.parseInt(req.getParameter("pageNo"), 1);
        int pageSize = DataUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE);

        //调用Servlet方法 获取Page对象
        Page<Furn> page = furnsService.page(pagNo, pageSize);
        System.out.println(page);
        //将page放入request域
        req.setAttribute("page", page);
        //请求转发
        req.getRequestDispatcher("/views/manage/furn_manage.jsp").forward(req, resp);

    }
}
